﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml.Linq;
using OauthProvider;

namespace Chat_WebServer.Controllers
{
    public class OAuthFriendController : ApiController
    {
        private static IOAuthProvider provider;

        public OAuthFriendController()
        {
            var consumerStore = new ConsumerStore();
            SimpleTokenStore tokenStore = new SimpleTokenStore();
            provider = new OAuthProvider(tokenStore,
                                   new ConsumerValidationInspector(consumerStore),
                                   new OAuth10AInspector(tokenStore));
        }

        // Lay danh sach ban be va cap nhat tinh trang
        public IEnumerable<MyFriend> Get()
        {
            IOAuthContext context = new OAuthContextBuilder().FromUri(HttpMethod.Get.ToString(), Request.RequestUri);
            try
            {
                provider.AccessProtectedResourceRequest(context);

                var accessToken = (MiniAccessToken)TokenUtility.GetToken(context.Token, TokenType.Access);

                string userName = accessToken.UserName;
                List<MyFriend> friends = new List<MyFriend>();
                using (var db = new AccountEntities())
                {
                    var temp = db.Friends.ToList().FirstOrDefault(f => f.UserName.Trim() == userName);
                    XElement xFriends = XElement.Parse(temp.Friends);
                    foreach (XElement friend in xFriends.Elements())
                    {
                        MyFriend f = new MyFriend();
                        string username = friend.Value;
                        f.Username = username;
                        if (AccountController.onlines.IndexOf(username) >= 0)
                            f.IsOnl = 1;
                        else
                            f.IsOnl = 0;
                        friends.Add(f);
                    }
                    if (friends.Count > 0)
                        return friends;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            return null;
        }
    }
}
